#include <stdio.h>
#include <stdlib.h>
#include <usart.h>
#include <delays.h>
#include <i2c.h>
#include <SW_i2c.h>
#include <p18f26k80.h>
#include <delays.h>


void soundINIT(void);
void CLK(unsigned char state);
void DATA(unsigned char state);
void stopSound(void);
void playPotionSong(int file);
void playIngredientSong(void);
void playSound(unsigned int file);

// definitions
void soundINIT(void) {

    TRISBbits.TRISB5 = 0;              //clk
    TRISBbits.TRISB4 = 0;              //data
    CLK(1);                                // Set ACLK to HIGH
    DATA(1);                               // set ADATA to HIGH
}

void CLK(unsigned char state) {
    if(state == 1)
        LATBbits.LATB5 = 1;

    if(state == 0)
        LATBbits.LATB5 = 0;
}

void DATA(unsigned char state) {
    if(state == 1)
        LATBbits.LATB4 = 1;

    if(state == 0)
        LATBbits.LATB4 = 0;
}

void playSound(unsigned int file) {

    int i = 15;
    int A[16];

    OSCCONbits.IRCF0=0;
    OSCCONbits.IRCF1=1;
    OSCCONbits.IRCF2=1;

    //Wait for Frequency
    while(OSCCONbits.HFIOFS != 1);



    for(; i >= 0; i--) {
       A[i] = file & 1;
       file >>= 1;
    }

    CLK(0);
    DATA(A[0]);

    // delay 20 ms
    Delay10KTCYx(32);

    for(i = 1; i < 16 ; i++) {
        CLK(1);
        Delay1KTCYx(3);    // delay 200 us
        Delay100TCYx(2);

        CLK(0);
        DATA(A[i]);
        Delay1KTCYx(3);    // delay 200 us
        Delay100TCYx(2);
    }
    CLK(1);
    DATA(1);

    OSCCONbits.IRCF0=1;
    OSCCONbits.IRCF1=1;
    OSCCONbits.IRCF2=1;

    //Wait for Frequency
    while(OSCCONbits.HFIOFS != 1);

}

void stopSound(void)
{
    int i;
    CLK(0);
    DATA(1);

    // delay 20 ms
    Delay10KTCYx(32);

        for( i = 1; i < 16 ; i++) {
        CLK(1);
        Delay1KTCYx(3);    // delay 200 us
        Delay100TCYx(2);

        CLK(0);
        DATA(1);
        Delay1KTCYx(3);    // delay 200 us
        Delay100TCYx(2);
    }
    CLK(1);
    DATA(1);
}

void playPotionSong(int file)
{

    if(file == 1)
    {

        playSound(0000);
    }

    if(file == 2)
    {
        playSound(0001);

    }

    if(file == 3)
    {

        playSound(0002);
    }

    if(file == 4)
    {

         playSound(0003);
    }
}

void playIngredientSong(void)
{
    //need different sound
    playSound(0000);
}
